package com.line.config.datasource;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.persistence.Column;

import org.springframework.jdbc.core.RowMapper;

public class BasicRowMapper<T> implements RowMapper<T> {
	private T t;

	public BasicRowMapper(Class<T> clazz) throws Exception {
		t = clazz.newInstance();
	}

	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		Field[] fields = t.getClass().getDeclaredFields(); // 通过反射取得所有字段信息
		for (Field field : fields) {
			if (field.isAnnotationPresent(Column.class)) {
				String fieldName = field.getName(); // 属性名
				Column column = field.getAnnotation(Column.class);
				String columnName = column.name(); // 获取注解名
				String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				try {
					Method method = t.getClass().getMethod(methodName, field.getType());
					Object object = rs.getObject(columnName);
					method.invoke(t, object);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return t;
	}

}